package com.zhulanhua.blogs.controller;

import com.zhulanhua.blogs.Utils.Code;
import com.zhulanhua.blogs.Utils.DozerUtils;
import com.zhulanhua.blogs.Utils.Result;
import com.zhulanhua.blogs.controller.VO.UserVO;
import com.zhulanhua.blogs.controller.params.LoginParams;
import com.zhulanhua.blogs.controller.params.UserUpdateInfoParams;
import com.zhulanhua.blogs.controller.params.userUpdateMd5Params;
import com.zhulanhua.blogs.controller.params.userUpdatePasswordParams;
import com.zhulanhua.blogs.domain.User;
import com.zhulanhua.blogs.service.ArticleService;
import com.zhulanhua.blogs.service.LoginService;
import com.zhulanhua.blogs.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Map;

/**
 * 用户接口
 * */
@RestController
@RequestMapping("/api/users")
@CrossOrigin
public class UserController {

    @Autowired
    UserService userService;
    @Autowired
    LoginService loginService;
    @Autowired
    DozerUtils dozerUtils;
    @Autowired
    ArticleService articleService;

    /**
     * 登录
     * @param loginParams
     * */
    @PostMapping("/login")
    public Result login(@Validated @RequestBody LoginParams loginParams){
        return new Result(Code.OK, loginService.Login(dozerUtils.convert(loginParams,User.class)));
    }

    /**
     * 获取博主信息
     * */
    @GetMapping("/info")
    public Result<UserVO> getDateil(){
        Map<String, Integer> map = articleService.getMap();
        UserVO dateils = dozerUtils.convert(userService.getDateils(), UserVO.class);
        dateils.setSupportSum(map.get("support"));
        dateils.setBrowseSum(map.get("browse"));
        dateils.setArticleSum(map.get("count"));
        return new Result(Code.OK, dateils);
    }

    /**
     * 修改博主基础信息
     * @param user
     * */
    @PutMapping("/update")
    public Result update(@RequestBody UserUpdateInfoParams user){
        userService.update(dozerUtils.convert(user,User.class));
        return Result.ok();
    }

    /**
     * 忘记密码，修改密码
     * @param u
     * */
    @PutMapping("/password")
    public Result updatePassword(@Validated @RequestBody userUpdatePasswordParams u){
        userService.updatePassword(dozerUtils.convert(u,User.class), u.getStr());
        return Result.ok();
    }

    /**
     * 忘记密码，发送验证码
     * @param u
     * */
    @GetMapping("/md5")
    public Result<String> getMD5(@Validated userUpdateMd5Params u){
        return new Result(Code.OK, userService.getMD5(dozerUtils.convert(u,User.class)));
    }

}
